package org.snail.base;

import org.apache.log4j.Logger;
import org.snail.constant.ErrCodeConstant;
import org.snail.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * 该目录是为了封装mongoTemplate，不要直接使用
 */
@Repository
public class MongoDBUtils {

    private static final Logger LOGGER = Logger.getLogger(MongoDBUtils.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存消息到mongoDB中
     */
    public Integer saveOneToMongo(Object saveObj, String mongoName) throws CommonException {
        int resultCode = -1;
        try{
            mongoTemplate.insert(saveObj, mongoName);
            resultCode = 1;
        }catch (Exception e){
            LOGGER.error("mongoDB单个对象保存失败！", e);
            throw new CommonException(ErrCodeConstant.DB_ERR, "mongoDB单个对象保存失败！");
        }
        return resultCode;
    }

    /**
     * 批量增加查询
     */
    public Integer batchSaveEntity(Collection collection, String mongoName) throws CommonException {
        int resultCode = -1;
        try{
            mongoTemplate.insert(collection, mongoName);
        }catch (Exception e){
            LOGGER.error("mongoDB批量保存对象失败！", e);
            throw new CommonException(ErrCodeConstant.DB_ERR, "mongoDB批量保存对象失败！");
        }
        return resultCode;
    }
}
